package com.example.controller;

import com.example.common.ResultBean;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户管理类-控制器
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/user/aaa")
    @ResponseBody
    public ResultBean list() {
        ResultBean result = new ResultBean();
        result.setData(userService.find());
        return result;
    }

    @PostMapping("/user/add1")
    @ResponseBody
    public ResultBean add(String username, String password, String realname) {
        ResultBean result = new ResultBean();
        if (username.length() > 45) {
            result.setCode("-1");
            result.setMsg("用户名过长");
            return result;
        }
        int i = userService.add(username, password, realname);
        if (i == 0) {
            result.setCode("-2");
            result.setMsg("该用户名已存在");
            return result;
        }
        return new ResultBean();
    }


    @RequestMapping("/user/update")
    @ResponseBody
    public ResultBean update(User user) {
        ResultBean result = new ResultBean();
        int i = userService.update(user);
        if (i > 0) {
            return result;
        } else {
            result.setCode("-1");
            result.setMsg("更新失败");
            return result;
        }
    }


    @RequestMapping("/user/delete")
    @ResponseBody
    public ResultBean delete(String id) {
        ResultBean result = new ResultBean();
        int i = userService.delete(id);
        if (i > 0) {
            return result;
        } else {
            result.setCode("-1");
            result.setMsg("删除失败");
            return result;
        }
    }

}
